<template lang="html">
  <div>
    <el-row class="mgb15">
      <el-button size="small" round type="primary" @click="handleAdd">新增</el-button>
      <!--  <el-button size="small" round type="danger" @click="deleteMany">批量删除</el-button>-->
    </el-row>
    <!-- 操作区----end -->
    <!-- 表格---start -->
    <el-table :data="tableData" v-loading="listLoading"  border stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column prop="itemName" label="name" width="150" align="center" >
      </el-table-column>
      <el-table-column prop="itemValue" label="value" width="150" align="center" >
      </el-table-column>
      <el-table-column prop="selector" label="selector" width="150" align="center">
      </el-table-column>
      <el-table-column prop="itemIndex" label="index"  width="150" align="center">
      </el-table-column>
      <el-table-column prop="attribute" label="attribute"  width="150" align="center">
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="230">
        <template slot-scope="scope">
          <el-button size="mini" plain type="info" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" plain type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total,sizes,prev, pager, next,jumper" :current-page="pageInfo.currentPage" :page-size="pageInfo.pageSize" :total="pageInfo.pageTotal" :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>
    <!-- 表格---end -->

    <!-- 编辑弹框---start -->
    <el-dialog  :title="formEditTitle" :visible.sync="dialogEdittVisible" width="700px" @close="closeDialog('formEdit')">
      <el-form :label-position="labelPosition" :label-width="labelWidth" :rules="rulesEdit" :disabled="formEditDisabled" :inline="true" ref="formEdit" :model="formEdit" class="demo-form-inline">
        <el-form-item label="name" prop="itemName">
          <el-input v-model="formEdit.itemName" placeholder="" ></el-input>
        </el-form-item>
        <el-form-item label="value" prop="itemValue">
          <el-input v-model="formEdit.itemValue" placeholder="" ></el-input>
        </el-form-item>
        <el-form-item label="selector" prop="selector">
          <el-input v-model="formEdit.selector" placeholder="" ></el-input>
        </el-form-item>
        <el-form-item label="index" prop="index">
          <el-input v-model="formEdit.itemIndex" placeholder="" ></el-input>
        </el-form-item>
        <el-form-item label="attribute" prop="attribute">
          <el-input v-model="formEdit.attribute" placeholder="" ></el-input>
        </el-form-item>
        <el-input  v-model="formEdit.matchUrlId" placeholder="matchUrlId" style="display : none" ></el-input>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEdittVisible = false">取 消</el-button>
        <el-button v-if="!formEditDisabled" type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import apis from '../../apis/apis';
  import vHead from '../common/Header.vue';
  import vSidebar from '../common/Sidebar.vue';
  import vTags from '../common/Tags.vue';
  import vFooter from '../common/Footer.vue';
  import bus from '../common/bus';
  import vHtml from "../parse/html.vue"
  export default {
    name: 'vhtml',
    data() {
      return {
        seleniumid:'',
        listLoading : false,//
        pageInfo: { //分页
          currentPage: 1,
          pageSize: 5,
          pageTotal: 0
        },
        formSearch: { //表单查询
          name: '',
          taskId:this.$route.query.taskId
        },
        formEdit: { //表单编辑
          itemName : '',
          itemValue : '',
          selector : '',
          item_index: '',
          attribute: ''
        },
        rulesEdit:  {
          name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
            { min: 2, max: 4, message: "长度在 2 到 4 个字符", trigger: "blur" }
          ],
          city:[{ required: true, message: "请输入城市", trigger: "blur" }]
          ,
          type: [{ required: true, message: "请选择类别", trigger: "change" }],
          gender: [{ required: true, message: "请选择性别", trigger: "change" }]
        },
        formEditTitle:'编辑',//新增，编辑和查看标题
        formEditDisabled:false,//编辑弹窗是否可编辑
        dialogEdittVisible: false,  //编辑弹框显示
        dialogType:'',//弹框类型：add,edit,show
        tableData: [],
        labelPosition: 'right', //lable对齐方式
        labelWidth: '80px', //lable宽度
        formLabelWidth: '120px',
        multipleSelection: []
      };
    },
    components: {
      vHead, vSidebar, vTags, vFooter,vHtml
    },
    created() {
      bus.$on('collapse', msg => {
        this.collapse = msg;
      })

      // 只有在标签页列表里的页面才使用keep-alive，即关闭标签之后就不保存到内存中了。
      bus.$on('tags', msg => {
        let arr = [];
        for (let i = 0, len = msg.length; i < len; i++) {
          msg[i].name && arr.push(msg[i].name);
        }
        this.tagsList = arr;
      })
    },
    computed:{

    },
    filters: {

    },
    mounted(){
      this.onSearch();
    },
    methods: {
      back (){
        this.$router.go(-1);
      },
      /**
       * 查询列表
       */
      onSearch(){
        var that=this;
        this.listLoading=true;
        let param_={
          matchUrlId : this.$route.query.matchUrlId
        };

        let param = Object.assign({},param_);
        apis.plugApi.getAllMatchUrlPlug(param)
          .then((data)=>{
            this.listLoading=false;
            if (data && data.data) {
              var json = data.data.data[0];
              if (data.data.successed) {
                this.seleniumid = json.selenium;
                that.getSelenium();
              }
              else if (json.message) {
                this.$message({message: json.message,type: "error"});
              }
            }
          })
          .catch((err)=>{
            this.listLoading=false;
            this.$message({message: 'selenium查询异常，请重试',type: "error"});
          });
      },
      getSelenium(){
        var that=this;
        this.listLoading=true;
        let param_={
          plugId :  this.seleniumid
        };
        let param = Object.assign({},param_,this.pageInfo);
        apis.plugApi.getAllMatchUrlPlugItemAttr(param)
          .then((data)=>{
            this.listLoading=false;
            if (data && data.data) {
              var json = data.data.rows;
              if (json && json.length > 0) {
                this.tableData = json;
                that.pageInfo.currentPage=data.data.curpage;
                that.pageInfo.pageTotal=data.data.total;
              } else if (json.message) {
                this.$message({message: json.message, type: "error"});
              }
            }
          })
          .catch((err)=>{
            this.listLoading=false;
            this.$message({message: 'selenium查询异常，请重试',type: "error"});
          });
      },
      handleSave(){
        if(this.dialogType=='add'){
          this.save();
        }
        else if(this.dialogType=='edit'){
          this.update();
        }
        else{
          this.$message({message: '操作异常',type: "error"});
        }
      },
      /**
       * 保存
       */
      save() {
        var that = this;
        this.$refs["formEdit"].validate(valid => {
          if(valid){
            let param_={
              plugId :  this.seleniumid
            };
            let param = Object.assign({}, param_, this.formEdit);
            apis.plugApi.insertMatchUrlPlugItemAttr(param)
              .then((data)=>{
                if(data && data.data){
                  var json=data.data;
                  if(json && json.successed){
                    this.$message({message: '执行成功',type: "success"});
                    this.dialogEdittVisible = false;
                    that.onSearch();
                    return;
                  }
                }
                this.$message({message: data.data.message,type: "error"});
              })
              .catch((err)=>{
                this.$message({message: '执行失败，请重试',type: "error"});
              });
          }


        });
      },
      /**
       * 更新
       */
      update() {
        var that = this;
        this.$refs["formEdit"].validate(valid => {
          if(valid){
            let param_={
              plugId :  this.seleniumid
            };
            let param = Object.assign({}, param_, this.formEdit);
            apis.plugApi.updateMatchUrlPlugItemAttr(param)
              .then((data)=>{
                console.log(data);
                if(data && data.data){
                  var json=data.data;
                  if(json.successed){
                    this.$message({message: '执行成功',type: "success"});
                    this.dialogEdittVisible = false;
                    that.onSearch();
                    return;
                  }
                }
                this.$message({message: '执行失败，请重试',type: "error"});
              })
              .catch((err)=>{
                this.$message({message: '执行失败，请重试',type: "error"});
              });
          }


        });
      },
      /**
       * 删除
       */
      handleDelete(index, rowData) {
        var that = this;
        var itemid=rowData.itemId;
        this.$confirm('此操作将永久删除该种子, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apis.plugApi.deleteMatchUrlPlugItemAttr({itemid : itemid})
            .then((data)=>{
              if(data.data.successed){
                that.onSearch();
              }
              this.$common.isSuccess(data,()=>{
                console.log("执行了");
              });
            })
            .catch((err)=>{
              debugger;
              this.$message({message: '执行失败，请重试',type: "error"});
            });

        }).catch(() => {
          this.$message({type: 'info',message: '已取消删除'});
        });

      },
      /**
       * 批量删除
       */
      deleteMany() {
        var ids= this.multipleSelection.map(item => item.id);
        if(ids.length==0){
          this.$message({message: '请选择要删除的项',type: "warn"});
          return;
        }
        debugger;
        this.$confirm('此操作将批量永久删除文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apis.msgApi.deleteBatch({ids:ids})
            .then((data)=>{
              this.$common.isSuccess(data,()=>{
                debugger;
                this.onSearch();
              });
            })
            .catch((err)=>{
              debugger;
              this.$message({message: '执行失败，请重试',type: "error"});
            });

        }).catch(() => {
          this.$message({type: 'info',message: '已取消删除'});
        });

      },
      onReset(){
        this.$refs['formSearch'].resetFields();
      },
      /**
       * 打开编辑弹窗
       */
      handleAdd() {
        this.dialogEdittVisible = true;
        this.$nextTick(()=>{
          this.dialogType='add';
          this.formEditTitle='新增';
          this.formEditDisabled=false;
        });


      },
      /**
       * 打开编辑弹窗
       */
      handleEdit(index, rowData) {
        //var msg = "索引是:" + index + ",行内容是:" + JSON.stringify(rowData);
        //this.$message({message: msg,type: "success"});
        this.dialogEdittVisible = true;//等dom渲染完，读取data中初始值，然后再复制，这样重置的是data中初始值
        this.$nextTick(()=>{
          this.dialogType='edit';
          this.formEditTitle='编辑';
          this.formEditDisabled=false;
          this.formEdit= Object.assign({}, rowData);
          this.formEdit.gender+='';//必须转换成字符串才能回显
        });
      },
      /**
       * 打开详情页
       */
      handleDetail(index,rowData){
        this.dialogEdittVisible = true;
        this.$nextTick(()=>{
          this.dialogType='show';
          this.formEditTitle='详情';
          this.formEditDisabled=true;
          this.formEdit= Object.assign({}, rowData) ;
          this.formEdit.gender+='';
        });

      },
      handleParse (index,rowData){
        this.$router.push ({
          path : 'filter' ,
          query : {
            taskId : rowData.taskId
          }
        })
      },
      /**
       * 关闭弹框，数据重置
       */
      closeDialog(formName){
        this.$refs[formName].resetFields();
      },
      /**
       * 分页大小切换
       */
      handleSizeChange(val) {
        this.pageInfo.pageSize = val;
        this.onSearch();
      },
      /**
       * 分页切换
       */
      handleCurrentChange(val) {
        this.pageInfo.currentPage = val;
        this.onSearch();
      },
      /**
       * 点击选择
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
        // this.$message({
        //     message: '选中的项是:' + JSON.stringify(this.multipleSelection),
        //     type: "success"
        // });
      },
      /**
       * 打开详情页
       */
      openDetail(row){
        this.$common.OpenNewPage(this,'detail',row);
      }


    }
  };
</script>


<style lang="css">
</style>


